package com.ruoyi.ldzlsb.controller;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestParam;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.ldzlsb.domain.SbEquipmentType;
import com.ruoyi.ldzlsb.service.ISbEquipmentTypeService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 设备类型Controller
 * 
 * @author ruoyi
 * @date 2025-06-24
 */
@RestController
@RequestMapping("/sb/equipment/type")
public class SbEquipmentTypeController extends BaseController
{
    @Autowired
    private ISbEquipmentTypeService sbEquipmentTypeService;

    /**
     * 查询设备类型列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SbEquipmentType sbEquipmentType)
    {
        startPage();
        List<SbEquipmentType> list = sbEquipmentTypeService.selectSbEquipmentTypeList(sbEquipmentType);
        return getDataTable(list);
    }

    /**
     * 查询所有设备类型（不分页，用于树状结构）
     */
    @GetMapping("/listAll")
    public AjaxResult listAll(SbEquipmentType sbEquipmentType)
    {
        List<SbEquipmentType> list = sbEquipmentTypeService.selectSbEquipmentTypeList(sbEquipmentType);
        return AjaxResult.success(list);
    }

    /**
     * 导出设备类型列表
     */
    @Log(title = "设备类型", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SbEquipmentType sbEquipmentType)
    {
        List<SbEquipmentType> list = sbEquipmentTypeService.selectSbEquipmentTypeList(sbEquipmentType);
        ExcelUtil<SbEquipmentType> util = new ExcelUtil<SbEquipmentType>(SbEquipmentType.class);
        util.exportExcel(response, list, "设备类型数据");
    }

    /**
     * 获取设备类型详细信息
     */
    @GetMapping(value = "/{typeId}")
    public AjaxResult getInfo(@PathVariable("typeId") Long typeId)
    {
        return success(sbEquipmentTypeService.selectSbEquipmentTypeByTypeId(typeId));
    }

    /**
     * 新增设备类型
     */
    @Log(title = "设备类型", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SbEquipmentType sbEquipmentType)
    {
        try {
            // 添加调试信息
            logger.info("新增设备类型 - 接收到的数据: {}", sbEquipmentType);
            logger.info("父类型ID: {}", sbEquipmentType.getParentTypeId());
            logger.info("typeSuperior: {}", sbEquipmentType.getTypeSuperior());
            
            // 设置创建时间和更新时间，避免使用前端传递的可能格式不一致的日期
            java.util.Date now = new java.util.Date();
            sbEquipmentType.setCreateTime(now);
            sbEquipmentType.setUpdateTime(now);
            
            int result = sbEquipmentTypeService.insertSbEquipmentType(sbEquipmentType);
            logger.info("新增设备类型 - 插入结果: {}", result);
            
            return toAjax(result);
        } catch (Exception e) {
            logger.error("新增设备类型失败", e);
            return error("新增失败：" + e.getMessage());
        }
    }

    /**
     * 修改设备类型
     */
    @Log(title = "设备类型", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SbEquipmentType sbEquipmentType)
    {
        try {
            // 设置更新时间，避免使用前端传递的可能格式不一致的日期
            sbEquipmentType.setUpdateTime(new java.util.Date());
            
        return toAjax(sbEquipmentTypeService.updateSbEquipmentType(sbEquipmentType));
        } catch (Exception e) {
            logger.error("修改设备类型失败", e);
            return error("修改失败：" + e.getMessage());
        }
    }

    /**
     * 删除设备类型
     */
    @Log(title = "设备类型", businessType = BusinessType.DELETE)
	@DeleteMapping("/{typeIds}")
    public AjaxResult remove(@PathVariable Long[] typeIds)
    {
        try {
            // 逐个检查每个类型是否可以删除
            for (Long typeId : typeIds) {
                Map<String, Object> checkResult = sbEquipmentTypeService.checkCanDelete(typeId);
                if (!(boolean) checkResult.getOrDefault("canDelete", false)) {
                    // 不能删除，返回原因
                    String reason = (String) checkResult.getOrDefault("reason", "未知原因");
                    return error("删除失败：" + reason);
                }
            }
            
            // 所有类型都可以删除，执行删除操作
        return toAjax(sbEquipmentTypeService.deleteSbEquipmentTypeByTypeIds(typeIds));
        } catch (Exception e) {
            logger.error("删除设备类型失败", e);
            return error("删除失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取设备类型树形结构
     */
    @GetMapping("/tree")
    public AjaxResult tree()
    {
        try {
            List<Map<String, Object>> treeData = sbEquipmentTypeService.getEquipmentTypeTree();
            return success(treeData);
        } catch (Exception e) {
            logger.error("获取设备类型树形结构失败", e);
            return error("获取设备类型树形结构失败：" + e.getMessage());
        }
    }
    
    /**
     * 检查设备类型编码是否已存在
     */
    @GetMapping("/checkCode")
    public AjaxResult checkTypeCode(@RequestParam("typeCode") String typeCode)
    {
        boolean exists = sbEquipmentTypeService.checkTypeCodeExists(typeCode);
        return AjaxResult.success("查询成功", exists);
    }
    
    /**
     * 检查设备类型编码是否已存在（排除当前ID）
     */
    @GetMapping("/checkCodeUnique")
    public AjaxResult checkTypeCodeUnique(
        @RequestParam("typeCode") String typeCode,
        @RequestParam(value = "typeId", required = false) Long typeId)
    {
        boolean exists = false;
        if (typeId != null) {
            // 编辑模式，排除自身
            exists = sbEquipmentTypeService.checkTypeCodeExistsExcludeSelf(typeCode, typeId);
        } else {
            // 新增模式
            exists = sbEquipmentTypeService.checkTypeCodeExists(typeCode);
        }
        return AjaxResult.success(exists);
    }
    
    /**
     * 生成设备类型编码
     */
    @GetMapping("/code")
    public AjaxResult generateTypeCode()
    {
        String code = sbEquipmentTypeService.generateTypeCode();
        return success(code);
    }

    /**
     * 根据类型名称生成编码
     */
    @GetMapping("/codeFromName")
    public AjaxResult generateTypeCodeFromName(@RequestParam(value = "typeName", required = true) String typeName)
    {
        String code = sbEquipmentTypeService.generateTypeCodeFromName(typeName);
        return success(code);
    }

    /**
     * 切换设备类型状态
     */
    @Log(title = "设备类型状态", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SbEquipmentType sbEquipmentType)
    {
        try {
            // 如果是停用操作，需要进行多重检查
            if ("1".equals(sbEquipmentType.getTypeStatus())) {
                // 1. 检查该类型下是否有非报废状态的设备
                int nonScrapCount = sbEquipmentTypeService.countNonScrapEquipmentByTypeId(sbEquipmentType.getTypeId());
                if (nonScrapCount > 0) {
                    return error("不能停用该类型，因为该类型下还有" + nonScrapCount + "台非报废状态的设备，只有设备在报废状态下才能停用类型");
                }
                
                // 2. 查询是否有启用状态的子类型
                List<SbEquipmentType> childTypes = sbEquipmentTypeService.selectChildTypesByParentId(sbEquipmentType.getTypeId());
                
                // 过滤出启用状态的子类型
                List<SbEquipmentType> activeChildTypes = new java.util.ArrayList<>();
                for (SbEquipmentType child : childTypes) {
                    if ("0".equals(child.getTypeStatus())) {
                        activeChildTypes.add(child);
                    }
                }
                
                // 如果有启用状态的子类型，不允许停用
                if (!activeChildTypes.isEmpty()) {
                    return error("不能停用该类型，因为有" + activeChildTypes.size() + "个子类型处于启用状态，请先停用所有子类型");
                }
            } 
            // 如果是启用操作，需要检查父类型是否为启用状态
            else if ("0".equals(sbEquipmentType.getTypeStatus())) {
                // 获取当前类型
                SbEquipmentType currentType = sbEquipmentTypeService.selectSbEquipmentTypeByTypeId(sbEquipmentType.getTypeId());
                if (currentType != null && currentType.getParentTypeId() != null && currentType.getParentTypeId() > 0) {
                    // 查询父类型状态
                    SbEquipmentType parentType = sbEquipmentTypeService.selectSbEquipmentTypeByTypeId(currentType.getParentTypeId());
                    if (parentType != null && "1".equals(parentType.getTypeStatus())) {
                        return error("不能启用该类型，因为其父类型\"" + parentType.getTypeName() + "\"处于停用状态，请先启用父类型");
                    }
                }
            }
            
            // 设置更新时间
            sbEquipmentType.setUpdateTime(new java.util.Date());
            
            // 执行状态更新
            return toAjax(sbEquipmentTypeService.updateSbEquipmentTypeStatus(sbEquipmentType));
        } catch (Exception e) {
            logger.error("更新设备类型状态失败", e);
            return error("更新设备类型状态失败：" + e.getMessage());
        }
    }
    
    /**
     * 检查设备类型是否可以删除
     */
    @GetMapping("/checkDelete/{typeId}")
    public AjaxResult checkCanDelete(@PathVariable("typeId") Long typeId)
    {
        Map<String, Object> result = sbEquipmentTypeService.checkCanDelete(typeId);
        return AjaxResult.success(result);
    }
}
